﻿#include "dlgbill.h"
#include "ui_dlgbill.h"

#include "dlgmain.h"

DlgBill::DlgBill(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DlgBill)
{
    ui->setupUi(this);

    m_pParent = parent;
    this->setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::Dialog);
    this->setFixedSize(g_nscreenwidth, g_nscreenheight);
    this->setGeometry(g_FirstScreen);
    ///////////////////////////////////////////////
    m_oldy1 = 0;
    nCurBillCount = 0;
    m_nFromChange = 0;
    m_tmpDisableSecond = 0;
    ui->lineEditDateTimeBillFrom->installEventFilter(this);
    ui->lineEditDateTimeBillTo->installEventFilter(this);
    ui->tableWidgetBill->viewport()->installEventFilter(this);
    ui->tableWidgetBill->verticalScrollBar()->installEventFilter(this);
    ui->labeltotalMoney->installEventFilter(this);
    QHeaderView *BillHorHead = ui->tableWidgetBill->horizontalHeader();
    BillHorHead->setObjectName("BillHorHead");
    BillHorHead->setFixedHeight(70);
    BillHorHead->setDefaultAlignment(Qt::AlignCenter);
    BillHorHead->setHighlightSections(false);
    ui->tableWidgetBill->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidgetBill->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidgetBill->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidgetBill->verticalHeader()->setVisible(false);
    ui->tableWidgetBill->verticalScrollBar()->setVisible(false);
    ui->tableWidgetBill->setShowGrid(true);
//    ui->tableWidgetBill->setFocusPolicy(Qt::NoFocus);
//    ui->tableWidgetBill->horizontalHeader()->setFocusPolicy(Qt::NoFocus);
    ui->tableWidgetBill->setColumnCount(8);
    ui->tableWidgetBill->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Stretch);
    ui->tableWidgetBill->horizontalHeader()->setSectionResizeMode(1,QHeaderView::Fixed);
    ui->tableWidgetBill->setColumnWidth(1, 400);
    ui->tableWidgetBill->horizontalHeader()->setSectionResizeMode(2,QHeaderView::Stretch);
    ui->tableWidgetBill->horizontalHeader()->setSectionResizeMode(3,QHeaderView::Fixed);
    ui->tableWidgetBill->setColumnWidth(3, 300);
    ui->tableWidgetBill->horizontalHeader()->setSectionResizeMode(4,QHeaderView::Stretch);
    ui->tableWidgetBill->horizontalHeader()->setSectionResizeMode(5,QHeaderView::Stretch);
    ui->tableWidgetBill->horizontalHeader()->setSectionResizeMode(6,QHeaderView::Fixed);
    ui->tableWidgetBill->setColumnWidth(6, 300);
    ui->tableWidgetBill->horizontalHeader()->setSectionResizeMode(7,QHeaderView::Stretch);
    QStringList tableHeaderBill;
    tableHeaderBill << tr(u8"编号") << tr(u8"日期时间")
                    << tr(u8"交易类型") << tr(u8"账户")
                    << tr(u8"交易金额") << tr(u8"操作员")
                    << tr(u8"账单号") << tr(u8"备注");
    ui->tableWidgetBill->setHorizontalHeaderLabels(tableHeaderBill);
    connect(ui->tableWidgetBill,&QTableWidget::itemClicked,this,&DlgBill::slotBillItemClicked);
    ui->lineEditDateTimeBillFrom->setText(QDateTime::currentDateTime().toString("yy-MM-dd hh:mm:ss"));
    ui->lineEditDateTimeBillTo->setText(QDateTime::currentDateTime().toString("yy-MM-dd hh:mm:ss"));
    //0初始化;1一卡通;2虚拟卡;3支付宝;4微信;5现金;6挂账;7其他;
    ui->comboBoxBillPayType->addItem(u8"全部");
    ui->comboBoxBillPayType->addItem(u8"一卡通");
    ui->comboBoxBillPayType->addItem(u8"虚拟卡");
    ui->comboBoxBillPayType->addItem(u8"支付宝微信");
    ui->comboBoxBillPayType->addItem(u8"现金");
    ui->comboBoxBillPayType->addItem(u8"挂账");
    ui->comboBoxBillPayType->addItem(u8"其他");
    ui->comboBoxBillPayType->setView(new QListView());
    //
    ui->widgetpopup->setFixedSize(422,360);
    ui->labelPopupImg->setFixedSize(389,238);
    ui->labelPopupText->setAlignment(Qt::AlignLeft);
    ui->labelPopupText->setWordWrap(true);
    QVBoxLayout *VPopup = new QVBoxLayout(ui->widgetpopup);
    VPopup->addWidget(ui->labelPopupImg);
    VPopup->addSpacing(5);
    VPopup->addWidget(ui->labelPopupText);
    ui->widgetpopup->hide();
    //
    m_pSliderTime = new MyTimeDialog();
    connect(m_pSliderTime,&MyTimeDialog::ClickedOK,this,&DlgBill::slotBillTimeChanged);
}

DlgBill::~DlgBill()
{
    delete ui;
}

void DlgBill::showDlgBill(uint LogInTime)
{
    m_TmpDateTimeF = QDateTime::fromTime_t(LogInTime);
    ui->lineEditDateTimeBillFrom->setText(m_TmpDateTimeF.toString("yy-MM-dd hh:mm:ss"));
    m_TmpDateTimeT = QDateTime::currentDateTime();
    ui->lineEditDateTimeBillTo->setText(m_TmpDateTimeT.toString("yy-MM-dd hh:mm:ss"));
    ui->comboBoxBillPayType->setCurrentIndex(0);
    while(0 != ui->tableWidgetBill->rowCount()){
        QTableWidgetItem *item = ui->tableWidgetBill->item(0,0); delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,1);  delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,2);  delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,3);  delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,4);  delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,5);  delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,6);  delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,7);  delete item; item = NULL;
        ui->tableWidgetBill->removeRow(0);
    }
    ui->tableWidgetBill->clearContents();
    ui->widgetpopup->hide();
    m_bDownQuery = true;
    ui->labeltotal_cardMoney->clear();
    ui->labeltotal_chargeRoomMoney->clear();
    ui->labeltotal_cashMoney->clear();
    ui->labeltotal_qrcodeMoney->clear();
    ui->labeltotalMoney->clear();

    this->show();
}

bool DlgBill::eventFilter(QObject *obj, QEvent *event)
{
    if(obj == ui->lineEditDateTimeBillFrom){
        if(QEvent::MouseButtonPress == event->type()){
            m_pSliderTime->SetTime(m_TmpDateTimeF);
            m_pSliderTime->SetTitle(u8"选择开始时间");
            m_pSliderTime->raise();
            m_pSliderTime->setVisible(true);
            m_nFromChange = 1;
        }
    }
    if(obj == ui->lineEditDateTimeBillTo){
        if(QEvent::MouseButtonPress == event->type()){
            m_pSliderTime->SetTitle(u8"选择结束时间");
            m_pSliderTime->SetTime(m_TmpDateTimeT);
            m_pSliderTime->raise();
            m_pSliderTime->setVisible(true);
            m_nFromChange = 2;
        }
    }
    if(obj == ui->tableWidgetBill->viewport()){
        if(QEvent::MouseButtonPress == event->type()){
            QMouseEvent *move = static_cast<QMouseEvent *>(event);
            m_oldy1 = move->pos().y();
        }
        if(QEvent::MouseMove == event->type()){
            QMouseEvent *move = static_cast<QMouseEvent *>(event);
            int newy1 = move->pos().y();
            int nCurrentVal = ui->tableWidgetBill->verticalScrollBar()->value();
            int nHeight = ui->tableWidgetBill->rowHeight(nCurrentVal);
            if (abs(newy1 - m_oldy1) >= nHeight){
                if(newy1 > m_oldy1) {
                    //up
                    ui->tableWidgetBill->verticalScrollBar()->setValue(nCurrentVal-1);
                }else if(newy1 < m_oldy1){
                    //down
                    ui->tableWidgetBill->verticalScrollBar()->setValue(nCurrentVal+1);
                    /////![账单查询]////////////////////////////////////////////////////////////////////////////
                    if(nCurBillCount > ui->tableWidgetBill->rowCount()){
                        if(m_bDownQuery){
                            m_bDownQuery = false;
//                            nCurBillCount += 4;
                            QJsonObject obj;
                            qint64 start_time = m_TmpDateTimeF.toTime_t();
                            qint64 end_time = m_TmpDateTimeT.toTime_t();
                            QString pay_type = ui->comboBoxBillPayType->currentText();
                            int nPayType = 0;
                            if(u8"全部" == pay_type) { nPayType = 0; }
                            else if(u8"一卡通" == pay_type){ nPayType = 1; }
                            else if(u8"虚拟卡" == pay_type){ nPayType = 2; }
                            else if(u8"支付宝微信" == pay_type){ nPayType = 3; }
                            else if(u8"现金" == pay_type){ nPayType = 5; }
                            else if(u8"挂账" == pay_type){ nPayType = 6; }
                            else { nPayType = 7; }
                            obj.insert("Cmd", "bill_query");
                            obj.insert("start_time", start_time);
                            obj.insert("end_time", end_time);
                            obj.insert("emp_id", 0);
                            obj.insert("pay_type", nPayType);
                            obj.insert("from", ui->tableWidgetBill->rowCount());
                            obj.insert("count", 4);
                            QJsonDocument doc;
                            doc.setObject(obj);
                            QString data = doc.toJson(QJsonDocument::Compact);
                            qDebug() << u8"向下滑" << ui->comboBoxBillPayType->currentText() << nPayType;

                            DlgMain *parent = (DlgMain*)m_pParent;
                            parent->QueryBill(data);
                        }
                    }
                }
                m_oldy1 = newy1;
            }
        }
    }
    return QDialog::eventFilter(obj, event);
}

void DlgBill::slotBillListResult(QString data)
{ 
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8(), &error);
    if(QJsonParseError::NoError != error.error)
        return;

    QJsonObject obj = doc.object();
    QJsonArray array = obj.take("Datas").toArray();
    nCurBillCount = 0;
    nCurBillCount = obj.take("Count").toInt();
    int nRowCount = ui->tableWidgetBill->rowCount();
    int nRevCount = array.size();
    if(0 == nRevCount)
    {
        ui->labeltotal_cardMoney->setText("0.0");
        ui->labeltotal_chargeRoomMoney->setText("0.0");
        ui->labeltotal_cashMoney->setText("0.0");
        ui->labeltotal_qrcodeMoney->setText("0.0");
        ui->labeltotalMoney->setText("0.0");
        return;
    }
    ui->tableWidgetBill->setRowCount(nRowCount + nRevCount);
    for(int i=0; i<nRevCount; i++)
    {
        ui->tableWidgetBill->setRowHeight(nRowCount + i, 55);
        QJsonObject childObj = array.at(i).toObject();
        QTableWidgetItem *item = new QTableWidgetItem(QString::number(nRowCount + i + 1));
        item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        ui->tableWidgetBill->setItem(nRowCount + i,0,item);
        uint paytime = childObj.take("Bill_paytime").toInt();
        QDateTime datePayTime = QDateTime::fromTime_t(paytime);
        item = new QTableWidgetItem(datePayTime.toString("yyyy-MM-dd hh:mm:ss"));
        item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        ui->tableWidgetBill->setItem(nRowCount + i,1,item);
        int nbill_paytype = childObj.take("Bill_paytype").toInt();
        QString bill_paytype;
        if(0 == nbill_paytype) { bill_paytype = u8""; }
        else if(1 == nbill_paytype) { bill_paytype = u8"一卡通"; }
        else if(2 == nbill_paytype) { bill_paytype = u8"虚拟卡"; }
        else if(3 == nbill_paytype) { bill_paytype = u8"支付宝微信"; }
        else if(4 == nbill_paytype) { bill_paytype = u8"支付宝微信"; }
        else if(5 == nbill_paytype) { bill_paytype = u8"现金"; }
        else if(6 == nbill_paytype) { bill_paytype = u8"挂账"; }
        else if(7 == nbill_paytype) { bill_paytype = u8"其他"; }
        item = new QTableWidgetItem(bill_paytype);
        item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        ui->tableWidgetBill->setItem(nRowCount + i,2,item);
        QString bill_account = childObj.take("Bill_account").toString();
        if(6 == nbill_paytype){
            bill_account = childObj.take("Telphone").toString();
        }
        item = new QTableWidgetItem(bill_account);
        ui->tableWidgetBill->setItem(nRowCount + i,3,item);
        item = new QTableWidgetItem(QString::number((double)childObj.take("Bill_paymoney").toInt()/100, 'f', 1));
        item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        ui->tableWidgetBill->setItem(nRowCount + i,4,item);
        item = new QTableWidgetItem(childObj.take("Bill_empname").toString());
        item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        ui->tableWidgetBill->setItem(nRowCount + i,5,item);
        item = new QTableWidgetItem(childObj.take("Bill_id").toString());
        item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        ui->tableWidgetBill->setItem(nRowCount + i,6,item);
        item = new QTableWidgetItem(childObj.take("Bill_remark").toString());
        ui->tableWidgetBill->setItem(nRowCount + i,7,item);
    }
    m_bDownQuery = true;
    //账单流水查询完毕，开始查询统计
    QJsonObject objSend;
    qint64 start_time = m_TmpDateTimeF.toTime_t();
    qint64 end_time = m_TmpDateTimeT.toTime_t();
    objSend.insert("Cmd", "bill_countmoney");
    objSend.insert("start_time", start_time);
    objSend.insert("end_time", end_time);
    QJsonDocument docSend;
    docSend.setObject(objSend);
    QString dataSend = docSend.toJson(QJsonDocument::Compact);

    DlgMain *parent = (DlgMain*)m_pParent;
    parent->QueryTotalMoney(dataSend);
}

void DlgBill::slotBillTotalMoney(QString data)
{
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8(), &error);
    if(QJsonParseError::NoError != error.error)
    {
        ui->labeltotal_cardMoney->setText("0.0");
        ui->labeltotal_chargeRoomMoney->setText("0.0");
        ui->labeltotal_cashMoney->setText("0.0");
        ui->labeltotal_qrcodeMoney->setText("0.0");
        ui->labeltotalMoney->setText("0.0");
        return;
    }
    QJsonObject obj = doc.object();
    double totalCard = (double)obj.take("totalCard").toInt()/100;
    double totalChargeRoom = (double)obj.take("totalChargeRoom").toInt()/100;
    double totalCash = (double)obj.take("totalCash").toInt()/100;
    double totalQrcode = (double)obj.take("totalQrcode").toInt()/100;
    double total = (double)obj.take("total").toInt()/100;
    ui->labeltotal_cardMoney->setText(QString::number(totalCard, 'f', 1));
    ui->labeltotal_chargeRoomMoney->setText(QString::number(totalChargeRoom, 'f', 1));
    ui->labeltotal_cashMoney->setText(QString::number(totalCash, 'f', 1));
    ui->labeltotal_qrcodeMoney->setText(QString::number(totalQrcode, 'f', 1));
    QString strTmpShow = QString("%1元  %2单").arg(QString::number(total, 'f', 1)).arg(nCurBillCount);
    ui->labeltotalMoney->setText(strTmpShow);
}

void DlgBill::slotBillDetail(QString data)
{
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8(), &error);
    if(QJsonParseError::NoError != error.error){
        qDebug() << "dlg_a_start slotBillDetail error";
        return;
    }
    QJsonObject obj = doc.object();
    QJsonArray array = obj.take("Dishes").toArray();
    QString strTotalText;
    QString strBill_id = obj.take("BillId").toString();
    for(int i=0; i<array.size(); i++)
    {
        QJsonObject childObj = array.at(i).toObject();
        QString othername = childObj.take("Bid_disothername").toString();
        int price = childObj.take("Bid_disprice").toInt();
        strTotalText += QString(u8"%1(￥%2)元 ").arg(othername).arg((double)price/100);
    }
    ui->labelPopupText->setText(strTotalText);
    /////////////////////////////
    ui->labelPopupImg->setScaledContents(true);
    QString urlPic = QString("%1/bill_imageShow/%2").arg(g_Url).arg(strBill_id+".jpg");
    QNetworkAccessManager net;
    QEventLoop loop;
    QNetworkReply *netReply = net.get(QNetworkRequest(urlPic));
    QObject::connect(netReply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();
    QPixmap pixmap;
    pixmap.loadFromData(netReply->readAll());
    ui->labelPopupImg->setPixmap(pixmap);
    /////////////////////////////////

    QPoint point = this->mapFromGlobal(QCursor::pos());
    if(400 > (1080 - point.y()))
        point.setY(point.y()-365);
    if(500 > (1920-point.x()))
        point.setX(point.x()-500);
    ui->widgetpopup->move(point);
    ui->widgetpopup->show();
}

void DlgBill::slotBillTimeChanged(QDateTime dateTime)
{
    if(m_nFromChange == 1){
        m_TmpDateTimeF = dateTime;
        ui->lineEditDateTimeBillFrom->setText(m_TmpDateTimeF.toString("yy-MM-dd hh:mm:ss"));
    }
    else if(m_nFromChange == 2){
        m_TmpDateTimeT = dateTime;
        ui->lineEditDateTimeBillTo->setText(m_TmpDateTimeT.toString("yy-MM-dd hh:mm:ss"));
    }
    else{
        qDebug()<<"slotBillTimeChanged time is wrong:"<<dateTime;
    }
}

void DlgBill::slotBillItemClicked(QTableWidgetItem *item)
{
    if(1 == item->column() || 6 == item->column()){
        int nCurRow = item->row();
        QString bill_id = ui->tableWidgetBill->item(nCurRow,6)->text();
        QJsonObject obj;
        obj.insert("Cmd","bill_detail");
        obj.insert("bill_id", bill_id);
        QJsonDocument doc;
        doc.setObject(obj);
        QByteArray strdata = doc.toJson(QJsonDocument::Compact);

        DlgMain *parent = (DlgMain*)m_pParent;
        parent->QueryBillDetail(QString(strdata));
    }else{
        ui->widgetpopup->hide();
    }
}

void DlgBill::on_btnBillReturn_clicked()
{
    DlgMain* parent = (DlgMain*)m_pParent;
    emit parent->sigExitApp();
}

void DlgBill::on_btnBillQuery_clicked()
{
    if (QDateTime::currentMSecsSinceEpoch() - m_tmpDisableSecond < 500){
        return;
    }
    m_tmpDisableSecond = QDateTime::currentMSecsSinceEpoch();
    //查询流水按钮
    while(0 != ui->tableWidgetBill->rowCount()){
        QTableWidgetItem *item = ui->tableWidgetBill->item(0,0); delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,1);  delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,2);  delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,3);  delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,4);  delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,5);  delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,6);  delete item; item = NULL;
        item = ui->tableWidgetBill->item(0,7);  delete item; item = NULL;
        ui->tableWidgetBill->removeRow(0);
    }
    ui->tableWidgetBill->clearContents();
    ui->widgetpopup->hide();
    m_bDownQuery = true;

    QString strTitle = QString(u8"计算中...");
    ui->labeltotal_cardMoney->setText(strTitle);
    ui->labeltotal_chargeRoomMoney->setText(strTitle);
    ui->labeltotal_cashMoney->setText(strTitle);
    ui->labeltotal_qrcodeMoney->setText(strTitle);
    ui->labeltotalMoney->setText(strTitle);

    QJsonObject obj;
    qint64 start_time = m_TmpDateTimeF.toTime_t();
    qint64 end_time = m_TmpDateTimeT.toTime_t();
    QString pay_type = ui->comboBoxBillPayType->currentText();
    int nPayType = 0;
    if(u8"全部" == pay_type) { nPayType = 0; }
    else if(u8"一卡通" == pay_type){ nPayType = 1; }
    else if(u8"虚拟卡" == pay_type){ nPayType = 2; }
    else if(u8"支付宝微信" == pay_type){ nPayType = 3; }
    else if(u8"现金" == pay_type){ nPayType = 5; }
    else if(u8"挂账" == pay_type){ nPayType = 6; }
    else { nPayType = 7; }

    obj.insert("Cmd", "bill_query");
    obj.insert("start_time", start_time);
    obj.insert("end_time", end_time);
    obj.insert("emp_id", 0);
    obj.insert("pay_type", nPayType);
    obj.insert("from", 0);
    obj.insert("count", 14);
    QJsonDocument doc;
    doc.setObject(obj);
    QString data = doc.toJson(QJsonDocument::Compact);

    DlgMain *parent = (DlgMain*)m_pParent;
    parent->QueryBill(data);
}
